// ========== 类型定义 ==========
interface NodeSchema {
  name: string;
  attrs?: Record<string, any>;
  renderHTML?(node: any): string; // 节点如何渲染成 HTML
}

interface ExtensionConfig {
  name: string;
  addCommands?(): Record<string, Function>;
  addNodes?(): NodeSchema[];
  onCreate?(): void;
  onDestroy?(): void;
}

export class Extension {
  name: string;
  private config: ExtensionConfig;

  constructor(config: ExtensionConfig) {
    this.name = config.name;
    this.config = config;
  }

  getNodes() {
    return this.config.addNodes?.() ?? [];
  }

  getCommands() {
    return this.config.addCommands?.() ?? {};
  }

  onCreate() {
    this.config.onCreate?.();
  }

  onDestroy() {
    this.config.onDestroy?.();
  }
}

// ========== Editor 核心类 ==========
export class Editor {
  private extensions: Extension[] = [];
  private nodes: Record<string, NodeSchema> = {};
  private commands: Record<string, Function> = {};
  private doc: any[] = []; // 文档存储

  constructor(options: { extensions?: Extension[]; content?: any[] } = {}) {
    if (options.extensions) {
      for (const ext of options.extensions) {
        this.registerExtension(ext);
      }
    }
    this.doc = options.content || [];
  }

  // ---- 核心功能 ----
  setContent(content: any[]) {
    this.doc = content;
  }

  getContent() {
    return this.doc;
  }

  render() {
    return this.doc
      .map((node) => {
        const schema = this.nodes[node.type];
        if (schema?.renderHTML) {
          return schema.renderHTML(node);
        }
        return `<div>[Unknown node: ${node.type}]</div>`;
      })
      .join("");
  }

  // ---- 插件管理 ----
  registerExtension(extension: Extension) {
    this.extensions.push(extension);

    // 注册节点
    for (const node of extension.getNodes()) {
      this.nodes[node.name] = node;
    }

    // 注册命令
    Object.assign(this.commands, extension.getCommands());

    extension.onCreate();
  }

  get commandsAPI() {
    return this.commands;
  }

  destroy() {
    for (const ext of this.extensions) {
      ext.onDestroy();
    }
  }
}

// ========== 插件示例 ==========

// 段落节点插件
const Paragraph = new Extension({
  name: "paragraph",
  addNodes() {
    return [
      {
        name: "paragraph",
        renderHTML(node) {
          return `<p>${node.content || ""}</p>`;
        },
      },
    ];
  },
});

// 加粗节点插件
const Bold = new Extension({
  name: "bold",
  addNodes() {
    return [
      {
        name: "bold",
        renderHTML(node) {
          return `<b>${node.content || ""}</b>`;
        },
      },
    ];
  },
});

// 日志插件（命令扩展）
const Logger = new Extension({
  name: "logger",
  addCommands() {
    return {
      log: (msg: string) => console.log(`[Logger]: ${msg}`),
    };
  },
  onCreate() {
    console.log("📝 Logger 插件已启动");
  },
  onDestroy() {
    console.log("📝 Logger 插件已卸载");
  },
});

// ========== 使用示例 ==========
const editor = new Editor({
  extensions: [Paragraph, Bold, Logger],
  content: [
    { type: "paragraph", content: "Hello " },
    { type: "bold", content: "World" },
  ],
});

// 渲染文档
console.log("初始 HTML 渲染结果:");
console.log(editor.render());

// 使用命令
editor.commandsAPI.log("编辑开始");

// 修改文档
editor.setContent([
  { type: "paragraph", content: "插件化开发 " },
  { type: "bold", content: "很有趣！" },
]);

console.log("\n修改后 HTML 渲染结果:");
console.log(editor.render());

// 销毁
editor.destroy();
